<template>
  <div class="common-container">
    <div class="header">
      <div class="header_left" style="display: flex;align-items: center;">
        <el-select size="small" v-model="searchSel" slot="prepend" placeholder="请选择" class="el_Select">
          <el-option label="用户名" value="1"></el-option>
          <el-option label="手机号" value="2"></el-option>
          <el-option label="昵称" value="3"></el-option>
        </el-select>
        <el-input :placeholder="placeholder" v-model="searchVal" style="width: 220px;margin-right: 15px;" size="small"
          maxlength="20" clearable @clear="searchClick" class="el_input">
          <el-button slot="append" :icon="loadingSearch ? 'el-icon-loading' : 'el-icon-search'" @click="searchClick">
          </el-button>
        </el-input>
        <el-select v-model="tenantId" filterable placeholder="请选择租户名称" size="small" style="width: 190px;"
          v-if="user.roleName == 'PLATFORM_ADMIN'" clearable @change="searchClick" @visible-change="enterprise"
          v-loadMore="loadMore">
          <el-option v-for="(item, i) in enterpriseList" :key="i" :label="item.name" :value="item.id">
          </el-option>
          <div class="div_box" v-loading="loading" :style="loading ? '' : 'display: none;'"> </div>
        </el-select>
      </div>
      <div class="header_right">
        <el-button size="small" style="margin-left: 15px;" icon="el-icon-plus" @click="onAdd"
          v-permission="{ action: 'member:add' }">新增
        </el-button>
      </div>
    </div>
    <div class="content">
      <el-table :data="tableData" height="calc(100% - 65px)" :header-cell-style="headerStyle" class="table" v-loading="loadingTable"
          element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(47, 51, 73, 0.3)">
        <el-table-column align="center" label="序号" type="index" width="80">
        </el-table-column>
        <el-table-column align="center" prop="username" label="用户名" min-width="80" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="scope.row.username">{{ scope.row.username }}</span>
            <span v-else style="color: #aaa">-</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="nickname" label="昵称" min-width="80" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="scope.row.nickname">{{ scope.row.nickname }}</span>
            <span v-else style="color: #aaa">-</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="mobile" label="手机号" min-width="80">
          <template slot-scope="scope">
            <span v-if="scope.row.mobile">{{ scope.row.mobile }}</span>
            <span v-else style="color: #aaa">-</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="role.name" label="角色名称" min-width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.role.description  }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="tenant.name" label="租户名称" min-width="100"
          v-if="user.roleName == 'PLATFORM_ADMIN'">
        </el-table-column>
        <el-table-column align="center" prop="createTime" label="创建时间" min-width="120" show-overflow-tooltip>
        </el-table-column>
        <el-table-column align="center" prop="avatar" label="头像" min-width="50">
          <template slot-scope="scope">
            <!-- <el-avatar :src="scope.row.avatar"  v-if="scope.row.avatar"></el-avatar>-->
            <el-avatar :src="src" v-if="scope.row.avatar == 1"></el-avatar>
            <el-avatar :src="src2" v-else-if="scope.row.avatar == 2"></el-avatar>
            <el-avatar :src="src3" v-else-if="scope.row.avatar == 3"></el-avatar>
            <el-avatar :src="src4" v-else-if="scope.row.avatar == 4"></el-avatar>
            <el-avatar :src="src5" v-else-if="scope.row.avatar == 5"></el-avatar>
            <el-avatar :src="src6" v-else-if="scope.row.avatar == 6"></el-avatar>
            <el-avatar v-else :src="defaultImg">
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="status" label="用户状态" min-width="80">
          <template slot-scope="scope">
            <el-switch slot="reference" :active-value="0" :inactive-value="1" v-model="scope.row.status"
              active-color="#7367F0" @change="changeSwitchGetId(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="management" label="操作" width="180" show-overflow-tooltip>
          <template slot-scope="scope">
            <!-- <el-tooltip class="item" effect="dark" content="单位分配" placement="bottom" v-if="user.roleName=='TENANT_ADMIN'">
              <i @click="onEdit2(scope.row)" class="iconfont assignPermissions-o tableBtnIcon"
                style="font-size: 20px;"></i>
            </el-tooltip> -->
            <el-tooltip class="item" effect="dark" content="编辑" placement="bottom"
              v-permission="{ action: 'member:edit' }">
              <i @click="onEdit(scope.row)" class="iconfont tianxie tableBtnIcon"></i>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="重置密码" placement="bottom"
              v-permission="{ action: 'member:reset' }">
              <i @click="onReset(scope.row)" class="iconfont zhongzhimima tableBtnIcon"></i>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除账号" placement="bottom"
              v-permission="{ action: 'member:delete' }">
              <i @click="onDel(scope.row.id)" class="iconfont shanchu tableBtnIcon"></i>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- <pagination @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" :page="page"
          :limit="limit" :total="total"></pagination> -->
      <pagination :total="total" :page.sync="page" :limit.sync="limit" @pagination="userList" class="pagination" />
    </div>
    <!-- 新增弹框 -->
    <addUser ref="refAdd" :roleList="roleList" :enterpriseList="enterpriseList"></addUser>
    <AddOrgUser ref="refAddOrgUser" :roleList="roleList" :enterpriseList="enterpriseList"></AddOrgUser>
    <!-- 修改弹框 -->
    <editUser ref="refEditUser" :editRowInfo="editRowInfo" :roleList="roleList"></editUser>
    <!-- 重置密码弹框 -->
    <resetPassword ref="refResetPassword" :submitUserInfo="submitUserInfo"></resetPassword>

    <Allot ref="refAllot" :editRowInfo="editRowInfo2" :dataList='dataList' :checkedkeys='checkedkeys'></Allot>

  </div>
</template>

<script>
import Tree from "@components/tree";
import tableStyleMixin from "@mixin/table-style";
import Pagination from "@components/Pagination.vue";
import AddUser from "./components/AddUser.vue"; //新增组件
import AddOrgUser from "./components/AddOrgUser.vue"; //新增组件
import EditUser from "./components/EditUser.vue"; //修改组件
import ResetPassword from "./components/ResetPassword.vue"; //重置密码组件
import Allot from "./components/Allot.vue"; //分配单位组件
import {
  reqAssignRoleList,
  getuserList,
  delUser,
  reqTenantList,
  disableUser,
  reqOrgList,
} from "@/api/api";
import { mapState } from "vuex";
import loadMore from "@mixin/loadMore";

export default {
  name: "member",
  components: {
    Tree,
    Pagination,
    AddUser,
    EditUser,
    ResetPassword,
    Allot,
    AddOrgUser
  },
  mixins: [tableStyleMixin, loadMore],
  data() {
    return {
      defaultImg: require("@assets/images/portrait.png"),
      src: require("@assets/images/touxiang1.png"),
      src2: require("@assets/images/touxiang2.png"),
      src3: require("@assets/images/touxiang3.png"),
      src4: require("@assets/images/touxiang4.png"),
      src5: require("@assets/images/touxiang5.png"),
      src6: require("@assets/images/touxiang6.png"),
      searchSel: "1", //用户名/手机号//昵称
      searchVal: "",
      nickname: "",
      tenantId: "",//租户
      enterpriseList: [],
      sysInstanceIndex: 1,
      sysInstanceTotalPages: 10,
      loading: false,
      flag: true,
      loadingSearch: false, //查询按钮loading
      roleList: [], //角色列表
      search_val: "",
      page: 1,
      limit: 10,
      total: 100,
      tableData: [],
      loadingTable:false,
      editRowInfo: {}, //修改那行的用户信息
      editRowInfo2: {},
      submitUserInfo: {}, //提交的信息（重置密码用(mobile+id)）
      enterpriseList: [], // 租户列表
      dataList: [], //单位列表
      checkedkeys: [], //默认勾选的节点的 key 的数组
    };
  },
  mounted() {
    // let element = this.$el.querySelector('.header')
    // let width = element.offsetWidth
    // // console.log(width);
    // this.width=width
    // // 动态设置样式
    // if(width>1500){
    //   this.$el.querySelector('.el-input-group__prepend').style.cssText =
    //             'border-left: none !important;border-top: none !important;border-bottom: none !important;';
    // }else{
    //   this.$el.querySelector('.el-input-group__prepend').style.cssText =
    //             'border-left: none !important;border-bottom: none !important;';
    // }
  },
  computed: {
    ...mapState(["user", "companyId"]),
    placeholder() {
      if (this.searchSel == 1) {
        return '请输入用户名'
      } else if (this.searchSel == 2) {
        return '请输入手机号'
      } else {
        return '请输入昵称'
      }
    }
  },
  methods: {
    async loadMore() {
      if (this.sysInstanceIndex >= Math.ceil(this.sysInstanceTotalPages / 10)) return
      this.sysInstanceIndex++
      this.loading = true;
      // 获取列表数据的方法
      await this.getEnterpriseList2()
      this.loading = false;
    },
    // 下拉请求列表
    enterprise(val) {
      if (val && this.flag) {
        this.getEnterpriseList2();
        this.flag = false;//只执行一次
      }
    },
    // 获取租户列表
    async getEnterpriseList2() {
      var res = await reqTenantList(this.sysInstanceIndex, 10);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.sysInstanceTotalPages = res.data.total
      this.enterpriseList = [...this.enterpriseList, ...res.data.rows]
    },
    // 清空
    clearNickname() {
      this.page = 1;
      this.limit = 10;
      this.userList();
    },
    // 获取租户列表
    async getEnterpriseList() {
      this.enterpriseList = [];
      var res = await reqTenantList(1, 999);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      let that = this;
      res.data.rows.forEach((e) => {
        that.enterpriseList.push({ id: e.id, name: e.name });
      });
    },
    //查询
    async searchClick() {
      this.page = 1;
      this.limit = 10;
      this.loadingSearch = true;
      await this.userList();
      this.loadingSearch = false;
    },
    handleSizeChange() { },
    handleCurrentChange() { },
    changeSwitchGetId(row) {
      if (row.status == 1) {
        this.$confirm("此操作将停用该用户, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            row.status = 1;
            let res = await disableUser({
              userId: row.id,
              status: row.status,
            });
            this.$modal.notifySuccess("停用成功");
          })
          .catch(() => {
            row.status = 0;
          });
      } else {
        this.$confirm("此操作将启用该用户, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            row.status = 0;
            let res = await disableUser({
              userId: row.id,
              status: row.status,
            });
            this.$modal.notifySuccess("启用成功");
          })
          .catch(() => {
            row.status = 1;
          });
      }
    },
    onEdit(row) {
      this.getAssignRoleList(); // 获取角色列表
      this.editRowInfo = JSON.parse(JSON.stringify(row));
      this.$refs.refEditUser.dialogVisible = true;
    },
    // 单位分配
    async onEdit2(row) {
      await this.getDataList(row);
      this.editRowInfo2 = JSON.parse(JSON.stringify(row));
      this.$refs.refAllot.dialogVisible = true;
    },
    // 获取单位列表
    async getDataList(row) {
      var res2 = await reqOrgList( {
        userId: this.user.userId,
        roleName: this.user.roleName,
        tenantId: this.user.tenantId,
      });
      if (res2.code !== 20000) return this.$modal.notifyWarning(res2.message);
      let { rows } = res2.data;
      this.dataList = rows;

      // 选中的节点
      var res = await reqOrgList({
        userId: row.id,
        roleName: row.role.name,
        tenantId: row.tenant.id,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.checkedkeys = [];
      res.data.rows.forEach((item) => {
        this.checkedkeys.push(item.id);
      });
      this.checkedkeys = [...new Set(this.checkedkeys)];//数组去重
    },
    onReset(row) {
      // console.log(row);
      this.submitUserInfo = JSON.parse(JSON.stringify(row));
      this.$refs.refResetPassword.dialogVisible = true;
    },
    onAdd() {
      // 租户创建单位||园区 TENANT_ADMIN-租户
      if (this.user.roleName === "TENANT_ADMIN" || this.user.roleName === "ORG_ADMIN" ||this.user.roleName === "UNIT_ADMIN" ||this.user.roleName === "INSTERALL_USER") {
        this.getAssignRoleList(); // 获取角色列表
        this.$refs.refAddOrgUser.dialogVisible = true;
        return;
      }
      // 运维创建租户  PLATFORM_ADMIN-运维
      if (this.user.roleName === "PLATFORM_ADMIN") {
        this.getEnterpriseList(); // 获取租户列表
      }
      
      this.getAssignRoleList(); // 获取角色列表
      this.$refs.refAdd.dialogVisible = true;
    },
    // 获取角色列表  不同角色获取不同的角色列表
    async getAssignRoleList() {
      this.roleList = [];
      let res = await reqAssignRoleList(this.user.userId, {
        name: this.user.roleName,
      });
      // console.log(res);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.roleList = res.data.rows;
    },
    async onDel(id) {
      const result = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => { });
      if (result !== "confirm") return;
      let res = await delUser(id);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifySuccess("删除用户成功");
      this.page = 1;
      this.limit = 10;
      this.userList();
    },
    // 获取用户列表
    async userList() {
      let { searchSel, username, mobile, searchVal, nickname } = this;
      if (searchSel == 1) {
        username = searchVal;
        mobile = "";
        nickname = '';
      } else if (searchSel == 2) {
        mobile = searchVal;
        username = "";
        nickname = '';
      } else {
        nickname = searchVal;
        mobile = "";
        username = "";
      }
      this.loading = true;
      this.loadingTable=true;
      let res = await getuserList(this.page, this.limit, {
        //   mobile: this.searchForm.mobile,
        id: this.user.userId,
        roleId: this.user.roleId,
        tenantId: this.tenantId ? this.tenantId : this.user.tenantId,
        // queryCondition: this.search_val,
        //   username: this.searchForm.username,
        roleName: this.user.roleName,
        username,
        nickname,
        mobile
      });
      this.loadingTable=false;
      this.loading = false;
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.tableData = res.data.rows;
      this.total = res.data.total;
      if (res.data.total < 10) return;
      //   this.scollTop();
    },
  },
  created() {
    this.userList();
  },
};
</script>

<style scoped lang="less">
@import url("~@views/style/tablePage.less");

::v-deep .el-button--small {
  background: #7367f0;
  color: #fff;
  border: none;
}


// 查询条件切换
::v-deep .el-input-group__prepend {
  // border-left: none !important;
  // border-top: none !important;
  // border-bottom: none !important;
  // border-right: none !important;
}

::v-deep .el-avatar>img {
  width: 100%;
}

// 搜索框
::v-deep .el_input .el-input__inner {
  border-left: none !important;
  border-radius: 0px !important;
}

::v-deep .el_Select .el-input__inner {
  border-radius: 0px !important;
}

// 查询条件切换
::v-deep .el_Select .el-input {
  width: 100px;
}
</style>